import { DatePicker, Divider, Form,message,Tree } from "antd";
import React from "react";
import styles from './index.less'
import { authManageDetail, authManageEdit, fetchMenuTreeByAdmin } from "@/services/tenantManagement";
import moment from "moment";

const { TreeNode } = Tree

class AuthManage extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      menuTree: {
        artificialMenu: [],
        knowledgeMenu: [],
        llmMenu: [],
        modelMenu: [],
        robotMenu: [],
        securityMenu: [],
        staffMenu: [],
        workOrderMenu:[]
      },
      checkedKeys: {
        artificialKeys: [],
        knowledgeKeys: [],
        llmKeys: [],
        modelKeys: [],
        robotKeys: [],
        securityKeys: [],
        staffKeys: [],
        workOrderKeys:[]
      },
      expandedKeys: {
        artificialKeys: [],
        knowledgeKeys: [],
        llmKeys: [],
        modelKeys: [],
        robotKeys: [],
        securityKeys: [],
        staffKeys: [],
        workOrderKeys:[]
      },
    }
  }

  componentDidMount(){
    if(this.props.onRef){
      this.props.onRef(this)
    }    
  }

  initData = () => {
    this.getMenusByAdmin()
  }

  getDetail = async (tenantId) => {
    const res = await authManageDetail({tenantId})
    this.getExpandedMenu(res.menuTree ? res.menuTree : []);
    this.setState({ menuTree: res.menuTree ? res.menuTree : [] }, () => {
      this.getSelectMenu(res ? res.menuTree.artificialMenu : [], "artificialKeys");
      this.getSelectMenu(res ? res.menuTree.knowledgeMenu : [], "knowledgeKeys");
      this.getSelectMenu(res ? res.menuTree.llmMenu : [], "llmKeys");
      this.getSelectMenu(res ? res.menuTree.modelMenu : [], "modelKeys");
      this.getSelectMenu(res ? res.menuTree.robotMenu : [], "robotKeys");
      this.getSelectMenu(res ? res.menuTree.securityMenu : [], "securityKeys");
      this.getSelectMenu(res ? res.menuTree.staffMenu : [], "staffKeys");
      this.getSelectMenu(res ? res.menuTree.workOrderMenu : [], "workOrderKeys");
    })
  }

  renderTreeNode = data => {
    return data.map(item => {
      if (item.children) {
        return (
          <TreeNode title={item.name} key={item.id}>{this.renderTreeNode(item.children)}</TreeNode>
        )
      };
      return <TreeNode title={item.name} key={item.id} />
    })
  }

  onExpand = (keys, type) => {
    let { expandedKeys } = this.state;
    expandedKeys[type] = keys;
    this.setState({ expandedKeys });
  }

  onCheck = (keys, type) => {
    let { checkedKeys } = this.state;
    checkedKeys[type] = keys;
    this.setState({ checkedKeys });
  };

  getSelectMenu = (data, type) => {
    const that = this;
    let { checkedKeys } = that.state;
    data.map(item => {
      if (item.children && item.children.length > 0) {
        const childrenChecked = item.children.filter(child => child.checked);
        if (childrenChecked.length === item.children.length) {
          checkedKeys[type].push(item.id);
        };
        that.getSelectMenu(item.children, type);
      } else {
        if (item.checked) {
          checkedKeys[type].push(item.id);
        };
      }
    });
    that.setState({ checkedKeys });
  }

  getMenusByAdmin = async () => {
    const { dispatch } = this.props;
    const res = await fetchMenuTreeByAdmin({id: 0})
    this.getExpandedMenu(res);
    this.setState({ menuTree: res ? res : [] }, () => {
      this.getSelectMenu(res ? res.artificialMenu : [], "artificialKeys");
      this.getSelectMenu(res ? res.knowledgeMenu : [], "knowledgeKeys");
      this.getSelectMenu(res ? res.llmMenu : [], "llmKeys");
      this.getSelectMenu(res ? res.modelMenu : [], "modelKeys");
      this.getSelectMenu(res ? res.robotMenu : [], "robotKeys");
      this.getSelectMenu(res ? res.securityMenu : [], "securityKeys");
      this.getSelectMenu(res ? res.staffMenu : [], "staffKeys");
      this.getSelectMenu(res ? res.workOrderMenu : [], "workOrderKeys");
    });
  }

  getExpandedMenu = res => {
    let { expandedKeys } = this.state;
    let treeData = (data, type) => {
      data.map(item => {
        if (item.children && item.children.length > 0) {
          expandedKeys[type].push(item.id);
          treeData(item.children, type);
        }
      })
    };
    treeData(res ? res.artificialMenu : [], "artificialKeys");
    treeData(res ? res.knowledgeMenu : [], "knowledgeKeys");
    treeData(res ? res.llmMenu : [], "llmKeys");
    treeData(res ? res.modelMenu : [], "modelKeys");
    treeData(res ? res.robotMenu : [], "robotKeys");
    treeData(res ? res.securityMenu : [], "securityKeys");
    treeData(res ? res.staffMenu : [], "staffKeys");
    treeData(res ? res.workOrderMenu : [], "workOrderKeys");
    console.log(expandedKeys);
    console.log(expandedKeys.knowledgeKeys);
    this.setState({ expandedKeys });
  }

  checkFormData = () => {
    this.props.form.validateFields((error,values) => {
      if(!error){
        const { checkedKeys,addressList,emailList,relCompanyList } = this.state;
        if (!checkedKeys && checkedKeys.artificialKeys.length === 0 &&
          checkedKeys.knowledgeKeys.length === 0 && checkedKeys.llmKeys.length === 0 &&
          checkedKeys.modelKeys.length === 0 && checkedKeys.robotKeys.length === 0 &&
          checkedKeys.securityKeys.length === 0 && checkedKeys.staffKeys.length === 0 && checkedKeys.workOrderKeys.length === 0
        ) {
          return message.error('请选择功能权限');
        }

        let valueObj = {
                menus: [
                ...checkedKeys.artificialKeys,
                ...checkedKeys.knowledgeKeys,
                ...checkedKeys.llmKeys,
                ...checkedKeys.modelKeys,
                ...checkedKeys.robotKeys,
                ...checkedKeys.securityKeys,
                ...checkedKeys.staffKeys,
                ...checkedKeys.workOrderKeys,
              ], 
            
            }
        
        if(this.props.tenantId){
          this.doEdit(valueObj)
        }else{
          this.props.setFormData({
            step:1,
            nextStep:2,
            value:valueObj
          })
        }
      }
    })
  }

  doEdit = async data => {
    const res = await authManageEdit({id:this.props.tenantId,...data})
    if(res.code != -1){
      message.info(res.message)
    }
  }

  render(){
    const { form:{getFieldDecorator},id,current } = this.props
    const { expandedKeys,menuTree,checkedKeys } = this.state;
    const formItemLayout = {
      labelCol: { span: 3 },
      wrapperCol: { span: 14 },
    };
    return(
      <div style={{display:current == 1 ? "block" : "none"}}>
        <Form {...formItemLayout}>
          <h3>功能模块</h3>
          <div className={styles.formMenuTree} style={{marginBottom:10}}>
            <span>
              <span>交互中心</span>
              <Tree
                checkable
                onExpand={e => this.onExpand(e, "modelKeys")}
                expandedKeys={JSON.parse(JSON.stringify(expandedKeys.modelKeys))}
                autoExpandParent={true}
                checkedKeys={checkedKeys.modelKeys}
                onCheck={e => this.onCheck(e, "modelKeys")}
                style={{ width: '300px', height: '300px', overflowX: 'hidden', overflowY: 'auto' }}
              >
                {this.renderTreeNode(menuTree.modelMenu)}
              </Tree>
            </span>
            <span>
              <span>工单中心</span>
              <Tree
                checkable
                onExpand={e => this.onExpand(e, "workOrderKeys")}
                expandedKeys={JSON.parse(JSON.stringify(expandedKeys.workOrderKeys))}
                autoExpandParent={true}
                checkedKeys={checkedKeys.workOrderKeys}
                onCheck={e => this.onCheck(e, "workOrderKeys")}
                style={{ width: '300px', height: '300px', overflowX: 'hidden', overflowY: 'auto' }}
              >
                {this.renderTreeNode(menuTree.workOrderMenu)}
              </Tree>
            </span>
            <span>
              <span>知识中心</span>
              <Tree
                checkable
                onExpand={e => this.onExpand(e, "knowledgeKeys")}
                expandedKeys={JSON.parse(JSON.stringify(expandedKeys.knowledgeKeys))}
                autoExpandParent={true}
                checkedKeys={checkedKeys.knowledgeKeys}
                onCheck={e => this.onCheck(e, "knowledgeKeys")}
                style={{ width: '300px', height: '300px', overflowX: 'hidden', overflowY: 'auto' }}
              >
                {this.renderTreeNode(menuTree.knowledgeMenu)}
              </Tree>
            </span>
            <span>
              <span>能力中心</span>
              <Tree
                checkable
                onExpand={e => this.onExpand(e, "llmKeys")}
                expandedKeys={JSON.parse(JSON.stringify(expandedKeys.llmKeys))}
                autoExpandParent={true}
                checkedKeys={checkedKeys.llmKeys}
                onCheck={e => this.onCheck(e, "llmKeys")}
                style={{ width: '300px', height: '300px', overflowX: 'hidden', overflowY: 'auto' }}
              >
                {this.renderTreeNode(menuTree.llmMenu)}
              </Tree>
            </span>
            <span>
              <span>数据中心</span>
              <Tree
                checkable
                onExpand={e => this.onExpand(e, "artificialKeys")}
                expandedKeys={JSON.parse(JSON.stringify(expandedKeys.artificialKeys))}
                autoExpandParent={true}
                checkedKeys={checkedKeys.artificialKeys}
                onCheck={e => this.onCheck(e, "artificialKeys")}
                style={{ width: '300px', height: '300px', overflowX: 'hidden', overflowY: 'auto' }}
              >
                {this.renderTreeNode(menuTree.artificialMenu)}
              </Tree>
            </span>
            <span>
              <span>客户中心</span>
              <Tree
                checkable
                onExpand={e => this.onExpand(e, "robotKeys")}
                expandedKeys={JSON.parse(JSON.stringify(expandedKeys.robotKeys))}
                autoExpandParent={true}
                checkedKeys={checkedKeys.robotKeys}
                onCheck={e => this.onCheck(e, "robotKeys")}
                style={{ width: '300px', height: '300px', overflowX: 'hidden', overflowY: 'auto' }}
              >
                {this.renderTreeNode(menuTree.robotMenu)}
              </Tree>
            </span>
            <span>
              <span>账号中心</span>
              <Tree
                checkable
                onExpand={e => this.onExpand(e, "staffKeys")}
                expandedKeys={JSON.parse(JSON.stringify(expandedKeys.staffKeys))}
                autoExpandParent={true}
                checkedKeys={checkedKeys.staffKeys}
                onCheck={e => this.onCheck(e, "staffKeys")}
                style={{ width: '300px', height: '300px', overflowX: 'hidden', overflowY: 'auto' }}
              >
                {this.renderTreeNode(menuTree.staffMenu)}
              </Tree>
            </span>
            <span>
              <span>安全中心</span>
              <Tree
                checkable
                onExpand={e => this.onExpand(e, "securityKeys")}
                expandedKeys={JSON.parse(JSON.stringify(expandedKeys.securityKeys))}
                autoExpandParent={true}
                checkedKeys={checkedKeys.securityKeys}
                onCheck={e => this.onCheck(e, "securityKeys")}
                style={{ width: '300px', height: '300px', overflowX: 'hidden', overflowY: 'auto' }}
              >
                {this.renderTreeNode(menuTree.securityMenu)}
              </Tree>
            </span>
          </div>
        </Form>
      </div>
    )
  }
}

export default Form.create()(AuthManage)